package cn.bgs.serviceedu.controller;


import cn.bgs.serviceedu.entity.Customer;
import cn.bgs.serviceedu.entity.Doctor;
import cn.bgs.serviceedu.entity.Hospital;
import cn.bgs.serviceedu.entity.Orders;
import cn.bgs.serviceedu.service.CustomerService;
import cn.bgs.serviceedu.service.DoctorService;
import cn.bgs.serviceedu.service.OrdersService;
import cn.bgs.serviceedu.vo.OrdersQuery;
import cn.bgs.serviceutils.utils.CSException;
import cn.bgs.serviceutils.utils.R;
import cn.bgs.serviceutils.utils.RedisUtils;
import cn.hutool.crypto.digest.MD5;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.amqp.rabbit.connection.CorrelationData;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.CachePut;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import java.util.Date;
import java.util.concurrent.TimeUnit;

/**
 * <p>
 * 订单表 前端控制器
 * </p>
 *
 * @author YiChen
 * @since 2021-10-20
 */
@Api(description = "订单表")
@Slf4j
@RestController
@RequestMapping("/serviceedu/orders")
public class OrdersController {

    @Autowired
    private OrdersService ordersService;
    @Autowired
    private RedisUtils redisUtils;
    @Autowired
    private RabbitTemplate rabbitTemplate;
    @Autowired
    private CustomerService customerService;
    @Autowired
    private DoctorService doctorService;

    @ApiOperation(value = "分页模糊查询")
    @PostMapping("/findAll/{doctorId}")
    @CachePut(key = "'OrdersList'",value = "OrdersList")
    public R findAll(@RequestBody OrdersQuery ordersQuery,@PathVariable Long doctorId){
        QueryWrapper<Orders> wrapper = Wrappers.<Orders>query()
                .eq(StringUtils.isNoneBlank(ordersQuery.getOrdersId()),"o.orders_id",StringUtils.trimToEmpty(ordersQuery.getOrdersId()))
                .eq(doctorId!=null && doctorId>0,"d.doctor_id",doctorId)
                .ge(ordersQuery.getCreateTimeMin()!=null,"o.create_time",ordersQuery.getCreateTimeMin())
                .le(ordersQuery.getCreateTimeMax()!=null,"o.create_time",ordersQuery.getCreateTimeMax())
                .orderByAsc("o.create_time");
        return R.ok().data("list",ordersService.findAllList(wrapper));
    }

    /**
     * 根据ID删除
     * @param pkId
     * @return
     */
    @ApiOperation(value = "根据ID删除")
    @DeleteMapping("/del/{pkId}")
    @CachePut(key = "'OrdersList'",value = "OrdersList")
    public R del(@PathVariable Integer pkId){
        boolean b = false;
        try {
            b = ordersService.removeById(pkId);
        } catch (Exception e) {
            throw new CSException(20001,"删除失败");
        }
        if (b){
            return R.ok().message("删除成功");
        }
        return R.error().message("删除失败");
    }


    /**
     * 根据ID单查
     * @param pkId
     * @return
     */
    @ApiOperation(value = "根据ID单查")
    @GetMapping("/findById/{pkId}")
    public R findById(@PathVariable Integer pkId){
        return   R.ok().data("list",ordersService.getById(pkId));
    }


    /**
     * 根据订单号查询订单
     * @param ordersId
     * @return
     */
    @ApiOperation(value = "根据订单号查询订单")
    @GetMapping("/findByIdOrders/{ordersId}")
    public Orders findByIdOrders(@PathVariable String ordersId){
        return ordersService.findByIdOrders(ordersId);
    }



    /**
     * 根据用户ID查询订单
     * @param customerId
     * @return
     */
    @ApiOperation(value = "根据用户ID查询订单")
    @GetMapping("/findByIdCustOrders/{customerId}")
    public R findByIdCustOrders(@PathVariable Integer customerId){
        return R.ok().data("list",ordersService.findByIdCustOrders(customerId));
    }



//
//    /**
//     * 订单生成
//     * @param orders
//     * @return
//     */
//    @ApiOperation(value = "生成订单")
//    @PostMapping("/addOrders")
//    public R addOrders(Orders orders){
//        try {
//            String ordersId=  System.currentTimeMillis() + "";
//            orders.setOrdersId(ordersId);
//            orders.setState(0);
//            boolean save = ordersService.save(orders);
//            if (save){
//                //设置分布式锁
//                redisUtils.setNx(ordersId,ordersId);
//                rabbitTemplate.convertAndSend("email.exchange","email.rotingkey",orders.getCustomerId()+"",new CorrelationData("1"));
//                rabbitTemplate.convertAndSend("shop.exchange","shop.rotingkey",ordersId,msg->{
//                    msg.getMessageProperties().setDelay(600000);
//                    return msg;
//                },new CorrelationData("下单消息"));
//                Customer byId = customerService.getById(orders.getCustomerId());
//                customerService.sendMail("您已在农务医生APP下单与医生的问诊订单，请您在10分钟内尽快支付,",
//                        byId.getCustomerEmail());
//                return  R.ok().data("data",orders).message("添加成功");
//            }
//        } catch (Exception e) {
//            throw new CSException(20001,"订单添加失败");
//        }
//
//        return   R.error().message("添加失败");
//    }
//
//
//    /**
//     * 支付订单
//     * @param ordersId
//     * @return
//     */
//    @ApiOperation(value = "订单付款")
//    @GetMapping("/shop/{ordersId}")
//    public R shop(@PathVariable String ordersId){
//        try {
//            Orders byIdOrders = ordersService.findByIdOrders(ordersId);
//            byIdOrders.getPkId();
//            if (ordersId.equalsIgnoreCase((String) redisUtils.get(ordersId))){
//                Integer state = byIdOrders.getState();
//                if (state==0){
//                    //修改订单状态为已支付
//                    byIdOrders.setState(1);
//                    ordersService.updateById(byIdOrders);
//                    log.info("支付成功");
//                    //释放锁
//                    redisUtils.del(ordersId);
//                    //给用户和医生发送提醒消息
//                    Customer byId = customerService.getById(byIdOrders.getCustomerId());
//                    customerService.sendMail("您已支付订单号为："+ordersId+"的订单，快去咨询问诊吧",
//                            byId.getCustomerEmail());
//                    Doctor byId1 = doctorService.getById(byIdOrders.getDoctorId());
//                    customerService.sendMail("有人下单了您的问诊，请尽快为用户解决问题",
//                            byId1.getDoctorEmail());
//                    return R.ok().message("支付成功");
//                }
//                return R.error().message("该订单已失效");
//            }
//        } catch (Exception e) {
//            throw new CSException(20001,"订单支付失败");
//        }
//
//        return R.error().message("订单不存在");
//    }
//
//
//    /**
//     * 验证支付密码
//     * @param payPwd
//     * @param customerId
//     * @return
//     */
//    @ApiOperation(value = "验证支付密码")
//    @GetMapping("/shopPwd/{payPwd}/{customerId}")
//    public R shopPwd(@PathVariable String payPwd,@PathVariable Integer customerId){
//        Customer byId = customerService.getById(customerId);
//
//        MD5 md5 = new MD5();
//        String s = md5.digestHex(payPwd);
//        if (!s.equals(byId.getPayPwd())){
//        throw new CSException(20001,"支付密码错误");
//        }
//        return R.ok();
//    }


}
